<template>
  <el-dialog class="add-bom-dialog" v-model="selectBomVisible" title="添加物料" width="600px" draggable>
    <el-row>
      <el-col :span="23">
        <el-form :model="orderEntityData" label-width="100px" size="default">
          <el-form-item label="选择物料：">
            <el-select v-model="orderEntityData.bomId" clearable filterable placeholder="选择物料"
                       @change="onBomSelect($event)"
                       style="width:100%;">
              <el-option v-for="item in bomList" :key="item.id" :label="item.code + ' <=> ' + item.name"
                         :value="item.id"/>
            </el-select>
          </el-form-item>
          <el-form-item label="物料单价：">
            <el-input v-model="orderEntityData.price"/>
          </el-form-item>
          <el-form-item label="订单数量：">
            <el-input v-model="orderEntityData.quantity"/>
          </el-form-item>
          <el-form-item label="交付日期：">
            <el-date-picker v-model="orderEntityData.deliveryDate" value-format="YYYY-MM-DD" type="date"
                            placeholder="选择交付日期" size="default"/>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
    <template #footer>
      <span class="dialog-footer">
        <el-button size="default" @click="closeBomSelectDialog">取消</el-button>
        <el-button size="default" type="primary" @click="confirmBomSelect">确定</el-button>
      </span>
    </template>
  </el-dialog>
  <div class="module-header">
    {{ `创建订单` }}
    <div class="module-header-search">
        <el-button size="default" type="primary" @click="backToOrderList">返回</el-button>
        <el-button size="default" type="primary" @click="createOrder">创建订单</el-button>
    </div>
  </div>
  <div class="create-order-view" :class="{'show-drag-over-state':isDragOver}" @dragover="onHolderDragOver"
       @dragleave="onHolderDragLeave" @drop="onHolderDragDrop">
    <div class="order-drag-view">
      <div class="order-drag-border">
        <span>将出库单文件拖拽到此处自动识别</span>
      </div>
    </div>
    <div class="input-order-view">
      <el-row>
        <el-col :span="16">
          <el-form :model="orderData" label-width="100px" size="default">
            <el-form-item label="订单编号：">
              <el-input v-model="orderData.orderNo"/>
            </el-form-item>
            <el-form-item label="订单日期：">
              <el-date-picker v-model="orderData.orderDate" value-format="YYYY-MM-DD" type="date"
                              placeholder="选择客户订单日期" size="default"/>
            </el-form-item>
            <el-form-item label="客户订单：">
              <el-input v-model="orderData.customerOrder"/>
            </el-form-item>
            <el-form-item label="订单客户：">
              <el-select v-model="orderData.customer" clearable filterable placeholder="选择下单客户"
                         @change="onBookingCustomerSelect" style="width: 100%">
                <el-option v-for="item in customerList" :key="item.id" :label="item.name" :value="item.id"/>
              </el-select>
            </el-form-item>
            <el-form-item label="结算客户：">
              <el-select v-model="orderData.paidCustomer" clearable filterable placeholder="选择结算客户"
                         @change="onPaidCustomerSelect" style="width: 100%">
                <el-option v-for="item in customerList" :key="item.id" :label="item.name" :value="item.id"/>
              </el-select>
            </el-form-item>
            <el-form-item label="交付客户：">
              <el-select v-model="orderData.deliveryCustomer" clearable filterable placeholder="选择交付客户"
                         @change="onDeliveryCustomerSelect" style="width: 100%">
                <el-option v-for="item in customerList" :key="item.id" :label="item.name" :value="item.id"/>
              </el-select>
            </el-form-item>
            <el-form-item label="交付地址：">
              <el-input v-model="orderData.deliveryAddress"/>
            </el-form-item>
          </el-form>
          <div style="padding-top: 20px">
            <el-table max-height="220" :data="orderEntities" style="width: 100%">
              <el-table-column prop="bomCode" label="物料编号" width="100" fixed="left"></el-table-column>
              <el-table-column prop="bomName" label="物料名称"></el-table-column>
              <el-table-column prop="price" label="物料单价" width="75"></el-table-column>
              <el-table-column prop="quantity" label="订单数量" width="75"></el-table-column>
              <el-table-column prop="deliveryDate" label="交付日期" width="100"></el-table-column>
              <el-table-column label="管理" fixed="right" width="140">
                <template #default="scope">
                  <div style="display:flex; justify-content: space-between">
                    <el-button size="small" @click="handleDetailEdit(scope.$index, scope.row)">编辑</el-button>
                    <el-button size="small" type="danger" @click="handleDetailDelete(scope.$index)">删除
                    </el-button>
                  </div>
                </template>
              </el-table-column>
            </el-table>
            <div>
              <div class="add-bom-container" @click="addOrderBom">
                <div class="">
                  <CirclePlusFilled/>
                </div>
                添加物料
              </div>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script lang="ts">
import {mixins, Options} from 'vue-class-component';
import {CirclePlusFilled, Edit} from "@element-plus/icons-vue";
import OrderModel from "@/models/OrderModel";
import {ocrOrder} from "@/apis/orders.api";
import TencentOcrResultModel, {TableDetection} from "@/models/TencentOcrResultModel";
import DictMixin from "@/mixins/dict.mixin";
import {BomEntityItem} from "@/models/common.model";
import BomModel from "@/models/BomModel";
import CustomerModel from "@/models/CustomerModel";
import {ElMessage, ElMessageBox} from "element-plus";
import {OrderDetailRequestModel, OrderRequestModel} from '@/models/OrderRequestModel';
import moment from "moment";
import DictionaryModel from "@/models/DictionaryModel";

@Options({
  components: {CirclePlusFilled, Edit}
})
export default class OrderCreateView extends mixins(DictMixin) {
  private dict: { [key: string]: number } = {"合成纸不干胶": 1, "普通不干胶纸": 2}

  private orderEntityData: BomEntityItem = new BomEntityItem();

  private orderData: OrderModel = new OrderModel();
  private orderEntities: BomEntityItem[] = [];

  private editRowIndex = -1;


  private customerList: CustomerModel[] = [];
  private bomList: BomModel [] = [];
  private selectBomVisible = false;


  private isDragOver = false

  created(): void {
    this.customerList = this.getUserDict<CustomerModel>('CUSTOMER_LIST');
    this.bomList = this.getUserDict<BomModel>('BOM_LIST');

    console.log(this.customerList)
    console.log(this.bomList)
  }

  onBookingCustomerSelect(index: number) {
    const customer: CustomerModel = this.customerList[index - 1]
    this.orderData.customer = customer.id;
    this.orderData.customerName = customer.name;
  }

  onDeliveryCustomerSelect(index: number) {
    const customer: CustomerModel = this.customerList[index - 1]
    this.orderData.deliveryCustomer = customer.id;
    this.orderData.deliveryCustomerName = customer.name;
  }

  onPaidCustomerSelect(index: number) {
    const customer: CustomerModel = this.customerList[index - 1]
    this.orderData.paidCustomer = customer.id;
    this.orderData.paidCustomerName = customer.name;
  }

  // 订单明细编辑
  handleDetailEdit(index: number, row: BomEntityItem): void {
    this.orderEntityData = row;
    this.editRowIndex = index;
    this.selectBomVisible = true;
  }

  // 订单明细删除
  handleDetailDelete(index: number): void {
    this.orderEntities.splice(index, 1);
  }

  confirmBomSelect() {
    this.selectBomVisible = false;
    if (this.orderEntityData.bomId) {
      const detailEntity: BomEntityItem = new BomEntityItem()

      detailEntity.bomId = this.orderEntityData.bomId;
      detailEntity.bomName = this.orderEntityData.bomName;
      detailEntity.bomCode = this.orderEntityData.bomCode;
      detailEntity.material = this.orderEntityData.material;
      detailEntity.quantity = this.orderEntityData.quantity;
      detailEntity.price = this.orderEntityData.price;
      detailEntity.deliveryDate = this.orderEntityData.deliveryDate;

      this.orderEntities.splice(this.editRowIndex > -1 ? this.editRowIndex : this.orderEntities.length - 1, this.editRowIndex > -1 ? 1 : 0, detailEntity);
      this.orderEntityData = new BomEntityItem();
      this.editRowIndex = -1
    }
  }

  // 确认添加手动创建的出库单
  confirmInputOrder() {
    const model: OrderRequestModel = new OrderRequestModel();
    model.orderNo = this.orderData.orderNo;
    model.orderDate = this.orderData.orderDate;
    model.customer = this.orderData.customer;
    model.customerName = this.orderData.customerName;
    model.deliveryCustomer = this.orderData.deliveryCustomer;
    model.deliveryCustomerName = this.orderData.deliveryCustomerName;
    model.deliveryAddress = this.orderData.deliveryAddress;
    model.paidCustomer = this.orderData.paidCustomer;
    model.paidCustomerName = this.orderData.paidCustomerName;
    model.detailEntities = this.orderEntities.reduce((previousValue: OrderDetailRequestModel[], currentValue: BomEntityItem): OrderDetailRequestModel[] => {
      const item: OrderDetailRequestModel = new OrderDetailRequestModel();
      item.bom = currentValue.bomId;
      item.bomCode = currentValue.bomCode;
      item.name = currentValue.bomName;
      item.price = currentValue.price;
      item.quantity = currentValue.quantity;
      item.material = currentValue.material;
      item.deliveryDate = currentValue.deliveryDate;
      previousValue.push(item);
      return previousValue;
    }, []);
    if (model.customer && model.orderDate && model.orderNo && model.detailEntities && model.detailEntities.length > 0) {
      console.log(model)
      // insertOrder(model).then((value: OrderModel) => {
      //   if (value.id) {
      //     ElMessageBox.confirm('订单创建成功，点击确定继续创建订单，点击取消关闭', '提示信息', {
      //       confirmButtonText: '确定',
      //       cancelButtonText: '取消',
      //       type: 'info',
      //     }).then(() => {
      //       this.orderEntityData = new BomEntityItem();
      //       this.editRowIndex = -1;
      //       this.selectBomVisible = false;
      //       this.orderData = new OrderModel();
      //       this.orderEntities.length = 0;
      //     }).catch(() => {
      //       this.orderEntityData = new BomEntityItem();
      //       this.editRowIndex = -1;
      //       this.selectBomVisible = false;
      //       this.cancelInputOrder();
      //       this.inputOrderVisible = false;
      //       this.createOrderVisible = false;
      //     })
      //   }
      // });
    } else {
      ElMessage.info({
        type: 'error',
        message: '信息填写不完整',
      })
    }
  }

  closeBomSelectDialog() {
    this.selectBomVisible = false;
    this.orderEntityData = new BomEntityItem()
  }

  onBomSelect(index: number) {
    if (this.bomList && this.orderEntityData) {
      const bom: BomModel | null = this.bomList[index - 1]
      this.orderEntityData.bomId = bom.id;
      this.orderEntityData.bomCode = bom.code;
      this.orderEntityData.bomName = bom.name;
      this.orderEntityData.price = bom.price;
    }
  }

  cancelInputOrder() {
    this.orderData = new OrderModel();
    this.orderEntities.length = 0;
  }

  addOrderBom() {
    this.orderEntityData = new BomEntityItem()
    this.selectBomVisible = true;
  }

  // 拖拽识别订单截图与pdf
  onHolderDragOver(e: DragEvent): void {
    e.preventDefault();
    this.isDragOver = true;
  }

  onHolderDragLeave(): void {
    this.isDragOver = false;
  }

  onHolderDragDrop(e: DragEvent): void {
    e.preventDefault();
    this.isDragOver = false;
    if (e.dataTransfer && e.dataTransfer.files.length > 0) {
      // 在此处处理上传文件的逻辑
      ocrOrder(e.dataTransfer.files[0]).then((value: TencentOcrResultModel) => {
        let orderData: OrderModel = new OrderModel();
        let orderEntities: BomEntityItem[] = [];
        if (value.TableDetections.length === 1) {
          if (value.TableDetections[0].Cells[0].Text.indexOf('龙润') > -1) {
            // 龙润订单
            ({order: orderData, entities: orderEntities} = this.resolveLROrderData(value.TableDetections));
          }
        } else if (value.TableDetections[0].Cells[0].Text.indexOf('统一') > -1) {
          // 统一订单
          ({order: orderData, entities: orderEntities} = this.resolveTYOrderData(value.TableDetections));
        }

        this.orderData = orderData;
        this.orderEntities = orderEntities;
      })
    }
  }

  resolveTYOrderData(tableDetections: TableDetection[]): { order: OrderModel, entities: BomEntityItem[] } {
    let orderData: OrderModel = new OrderModel();
    let orderEntities: BomEntityItem[] = [];
    orderData.orderNo = tableDetections[0].Cells[tableDetections[0].Cells.length - 5].Text;

    orderData.orderDate = moment(tableDetections[0].Cells[tableDetections[0].Cells.length - 3].Text, 'YYYY/MM/DD').format("YYYY-MM-DD");
    orderData.customerOrder = tableDetections[0].Cells[tableDetections[0].Cells.length - 5].Text;
    orderData.customer = '1';
    orderData.customerName = tableDetections[0].Cells[0].Text;
    //this.customerList.find(customer => customer.fullName.indexOf(orderData.customerName) > -1)?.id ?? -1;
    orderData.deliveryCustomer = '1'; //tableDetections[0].Cells[0].Text;
    orderData.deliveryCustomerName = tableDetections[0].Cells[0].Text;
    orderData.customer = Object.values(this.customerList).find(customer => customer.name.indexOf(orderData.customerName) > -1)?.id ?? 'UNKNOWN';
    orderData.status = "VERIFIED"
    tableDetections[1].Cells.length = tableDetections[1].Cells.length - (tableDetections[1].Cells.length % 9);
    for (let i = 9; i < tableDetections[1].Cells.length; i += 9) {
      if (!tableDetections[1].Cells[i].Text) {
        continue;
      }
      const entity: BomEntityItem = new BomEntityItem();
      entity.bomCode = tableDetections[1].Cells[i].Text;
      entity.bomName = tableDetections[1].Cells[i + 1].Text;
      entity.quantity = parseInt(tableDetections[1].Cells[i + 2].Text.replaceAll(',', ''));
      entity.price = parseFloat(tableDetections[1].Cells[i + 4].Text);
      entity.deliveryDate = moment(tableDetections[1].Cells[i + 7].Text, 'YYYY/MM/DD').format("YYYY-MM-DD");
      entity.note = tableDetections[1].Cells[i + 8].Text;
      entity.material = this.dict[tableDetections[1].Cells[i + 8].Text];
      entity.bomId = Object.values(this.bomList).find(bom => bom.code === entity.bomCode)?.id ?? -1;
      console.log(entity)
      orderEntities.push(entity)
    }
    return {order: orderData, entities: orderEntities};
  }

  resolveLROrderData(tableDetections: TableDetection[]): { order: OrderModel, entities: BomEntityItem[] } {
    // console.log(tableDetections.forEach())
    return {order: new OrderModel(), entities: []};
  }
}

</script>

<style scoped lang="scss">
.create-order-view {
  width: 100%;
  height: calc(100% - 50px);
  position: relative;

  .order-drag-view {
    display: none;
  }

  &.show-drag-over-state {
    .order-drag-view {
      pointer-events: none;
      position: absolute;
      z-index: 1000;
      width: 100%;
      height: 100%;
      background: rgba(0, 0, 0, 0.2);
      padding: 20px;
      display: block;

      .order-drag-border {
        border: dashed #eee 10px;
        height: 100%;
        width: 100%;
        display: flex;
        align-items: center;
        justify-content: center;

        span {
          font-size: 48px;
          color: #ddd;
        }
      }
    }
  }

  .input-order-view {
    padding: 40px;
  }
}

.add-bom-container {

  height: 60px;
  padding-top: 15px;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  line-height: 20px;
  cursor: pointer;

  & > div {
    height: 30px;
    width: 30px;
  }
}

.add-bom-dialog {
  .el-dialog__footer {
    text-align: center;
  }
}


</style>
<style lang="scss">
.create-order-dialog {
  .el-dialog__body {
    padding-bottom: 10px !important;
  }
}
</style>